import pika
import json




def send_to_rabbitmq(file_path, queue_name='prod_acceleratedtest_warn_msg3'):
    """
    读取文件内容并发送到RabbitMQ队列
    :param file_path: 要读取的文件路径
    :param queue_name: RabbitMQ队列名称，默认为prod_acceleratedtest_warn_msg3
    """
    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        # 将文件内容转换为JSON格式
        content = json.loads(content)



        # 设置RabbitMQ连接参数（请替换为实际值）
        credentials = pika.PlainCredentials(
            username='test',  # 替换为实际用户名
            password='Un9Q4Jxw^D8f'  # 替换为实际密码
        )

        # 建立RabbitMQ连接
        connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.16.152.203', port=5672, virtual_host='/',credentials=credentials))
        channel = connection.channel()

        # 声明队列
        channel.queue_declare(queue=queue_name, durable=True)

        # 发送消息
        # 循环发送100条
        for i in range(100):
            # 打印文件内容
            print(f"文件内容: {content}")
            channel.basic_publish(
                exchange='',
                routing_key=queue_name,
                body=str(content),
                # properties=pika.BasicProperties(
                #     delivery_mode=2,  # 使消息持久化
                # )
            )

        print(f"消息已发送到队列 {queue_name}")
        connection.close()

    except Exception as e:
        print(f"发生错误: {str(e)}")


# 使用示例
# 获取当前文件目录
import os

current_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接文件路径
file_path = os.path.join(current_dir, '数据.json')
send_to_rabbitmq(file_path)
